#include "route.hpp"
#include "db_manager.hpp"
#include <sstream>
#include <iomanip>

std::vector<RouteChange> RouteChange::getAll() {
    std::vector<RouteChange> changes;
    auto* mysql = DBManager::getInstance().getConnection();
    
    if (!mysql) {
        throw std::runtime_error("无法获取数据库连接");
    }
    
    const char* query = "SELECT id, modid, cmdid, version FROM RouteChange ORDER BY id DESC";
    if (mysql_query(mysql, query)) {
        throw std::runtime_error(std::string("查询失败: ") + mysql_error(mysql));
    }
    
    MYSQL_RES* result = mysql_store_result(mysql);
    if (!result) {
        throw std::runtime_error(std::string("存储结果失败: ") + mysql_error(mysql));
    }
    
    MYSQL_ROW row;
    while ((row = mysql_fetch_row(result))) {
        RouteChange change;
        change.id = std::stoi(row[0]);
        change.modid = std::stoi(row[1]);
        change.cmdid = std::stoi(row[2]);
        
        // 将版本号作为时间戳
        time_t timestamp = std::stol(row[3]);
        std::stringstream ss;
        ss << std::put_time(std::localtime(&timestamp), "%Y-%m-%d %H:%M:%S");
        
        change.time = ss.str();
        
        changes.push_back(change);
    }
    
    mysql_free_result(result);
    return changes;
}

bool RouteChange::insert(int modid, int cmdid) {
    auto* mysql = DBManager::getInstance().getConnection();
    
    if (!mysql) {
        throw std::runtime_error("无法获取数据库连接");
    }
    
    // 获取当前版本号
    const char* version_query = "SELECT version FROM RouteVersion ORDER BY id DESC LIMIT 1";
    if (mysql_query(mysql, version_query)) {
        throw std::runtime_error(std::string("查询版本号失败: ") + mysql_error(mysql));
    }
    
    MYSQL_RES* version_result = mysql_store_result(mysql);
    if (!version_result) {
        throw std::runtime_error(std::string("存储版本号结果失败: ") + mysql_error(mysql));
    }
    
    MYSQL_ROW version_row = mysql_fetch_row(version_result);
    if (!version_row) {
        mysql_free_result(version_result);
        throw std::runtime_error("未找到版本信息");
    }
    
    int current_version = std::stoi(version_row[0]);
    mysql_free_result(version_result);
    
    // 插入变更记录
    char query[256];
    snprintf(query, sizeof(query),
             "INSERT INTO RouteChange (modid, cmdid, version) VALUES (%d, %d, %d)",
             modid, cmdid, current_version);
    
    if (mysql_query(mysql, query) != 0) {
        throw std::runtime_error(std::string("插入失败: ") + mysql_error(mysql));
    }
    
    return true;
} 